package cn.hchaojie.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;

public class LuceneIndexer {
	public static void main(String[] args) throws IOException {
		// 创建一个IndexWriter对象
		IndexWriter indexWriter = new IndexWriter(
				// 索引库的创建路径
				FSDirectory.open(Paths.get("D:\\workspace\\workspace_stxy\\lucene-day01\\index")), 
				// 索引配置、文本分析器
				new IndexWriterConfig(new StandardAnalyzer()));
		
		// 把原始的文档转化成Document对象（把文档的信息封装到Field属性里面去）
		File file = new File("D:\\workspace\\workspace_stxy\\lucene-day01\\data\\spring.txt");
		Document doc = convertToDocument(file);
		
		// 使用IndexWriter把Document对象写到索引库里面
		indexWriter.addDocument(doc);
		
		indexWriter.close();
	}

	// 把原始的文档转化成Document对象
	private static Document convertToDocument(File file) throws FileNotFoundException {
		Document doc = new Document();
		
		// 把文件的每一个信息封装到Field对象里面去
		// 名字、路径、大小、内容
		
		Field nameField = new TextField("name", file.getName(), Store.YES);
		Field pathField = new StoredField("path", file.getAbsolutePath());
		Field sizeField = new LongPoint("size", file.length());
		Field contentField = new TextField("content", new BufferedReader(new FileReader(file)));
		
		doc.add(nameField);
		doc.add(pathField);
		doc.add(sizeField);
		doc.add(contentField);

		return doc;
	}
}
